package pub.cleangao.mybatis.execution;


import lombok.Data;
import lombok.EqualsAndHashCode;
import pub.cleangao.mybatis.runtime.Mode;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;


@EqualsAndHashCode(callSuper = true)
@Data
public class CreateExecution extends AbstractExecution {


    public static CreateExecution startInsert(String table) {
        CreateExecution execution = new CreateExecution();
        execution.setTable(table);
        execution.setColumnList(new ArrayList<>());
        execution.setValues(new ArrayList<>());
        return execution;
    }

    private String table;

    private List<String> columnList;

    private List<Object> values;


    @Override
    public Object runInDataSource(Connection connection) throws SQLException {
        if (table == null || table.trim().isEmpty()) {
            throw new SQLException("table name empty.");
        }
        String sqlLine = getSqlLine();
        PreparedStatement statement = connection.prepareStatement(sqlLine);
        for (int i = 0; i < values.size(); i++) {
            statement.setObject(i + 1, values.get(i));
        }
        // 日志打印输出
        if (Mode.DEBUG) {
            System.out.println("==> " + sqlLine);
            System.out.println("==> " + values);
            long start = System.currentTimeMillis();
            statement.execute();
            System.out.println("<== [" + statement.getUpdateCount() + "] " + (System.currentTimeMillis() - start) + "ms");
            return statement.getUpdateCount();
        }
        statement.execute();
        return statement.getUpdateCount();
    }

    private String getSqlLine() throws SQLException {
        StringBuilder sql = new StringBuilder();
        sql.append("INSERT INTO ");
        sql.append(table);
        if (columnList != null && !columnList.isEmpty()) {
            if (values == null || values.isEmpty() || columnList.size() != values.size()) {
                throw new SQLException("value input not match column num set.");
            }
            sql.append("(");
            for (String column : columnList) {
                sql.append(column);
                sql.append(",");
            }
            sql.delete(sql.length() - 1, sql.length());
            sql.append(")");
        }
        if (values == null || values.isEmpty()) {
            throw new SQLException("value set empty.");
        }
        sql.append(" VALUES(");
        for (Object value : values) {
            sql.append("?,");
        }
        sql.delete(sql.length() - 1, sql.length());
        sql.append(");");
        return sql.toString();
    }


}
